package cn.haoo.controller;

import cn.haoo.pojo.*;
import cn.haoo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private GreatService greatService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private CommentreadService commentreadService;

    /*注册页面*/
    @GetMapping("/regist")
    public String registUsre(Model model) {
        return "user/reg";
    }

    /*注册*/
    @PostMapping("/regist")
    public String registtoUser(Model model, User user) {
        System.out.println("开始注册了");
        System.out.println("user:" + user);
        if (!checkUserSet(model, user))
            return "/user/reg";
        setUserSex(user);
        userService.insertSelective(user);
        return "user/login";
    }

    /*登陆页面*/
    @GetMapping("/login")
    public String loginUser(Model model) {
        return "user/login";
    }

    /*登陆*/
    @PostMapping("/login")
    public String logintoUser(Model model, HttpSession session, User user) {
        String uno = user.getUno();
        String upass = user.getUpass();
        User usercheck = userService.selectByUno(uno);
        Boolean warn = true;
        System.out.println(user);
        System.out.println(usercheck);
        if (usercheck == null) {
            warn = false;
            model.addAttribute("nowarn", "是没见过的friend");
        } else if (!usercheck.getUpass().equals(upass)) {
            warn = false;
            model.addAttribute("passwarn", "是不认识的friend");
        }
        if (!warn) {
            return "user/login";
        }
        session.setAttribute("user", usercheck);
        return "redirect:/index";
    }

    /*登出*/
    @RequestMapping("/logout")
    public String logoutUser(HttpSession session) {
        session.removeAttribute("user");
        System.out.println("已退出登陆");
        return "redirect:/index";
    }

    /*用户主页*/
    @RequestMapping("/home")
    public String homeUser(Model model, HttpSession session) {
        //封装数据,可以在jsp页面取出并渲染
        System.out.println("开始处理home的数据");
        User owner = (User) session.getAttribute("user");
        List<Item> list = itemService.selectByUid(owner.getUid());
        System.out.println("这是owner拿到的list" + list);
        List<Commentread> commentreads=commentreadService.selectByUid(owner.getUid());
        model.addAttribute("owner",owner);
        model.addAttribute("comm",commentreads);
        model.addAttribute("list", ShowIndexView(list));
        return "/user/home";
    }

    /*其他用户主页*/
    @RequestMapping("/neighbor")
    public String homeUserbyUid(Model model, HttpSession session,int uid) {
        //封装数据,可以在jsp页面取出并渲染
        System.out.println("开始处理home的数据");
        User owner = userService.selectByPrimaryKey(uid);
        List<Item> list = itemService.selectByUid(owner.getUid());
        System.out.println("这是owner拿到的list" + list);
        List<Commentread> commentreads=commentreadService.selectByUid(owner.getUid());
        model.addAttribute("owner",owner);
        model.addAttribute("comm",commentreads);
        model.addAttribute("list", ShowIndexView(list));
        return "/user/home";
    }

    /*基本设置*/
    @RequestMapping("/set")
    public String setUser(Model model) {
        return "/user/set";
    }



    /*更新用户信息*/
    @RequestMapping("/upload1")
    public String userUpload1(HttpSession session, Model model, User user) {
        //用户备注
        if (user.getUother() == null) {
            user.setUother("这个咸鱼太懒了什么都没写");
        }
        //用户性别格式化
        setUserSex(user);
        //更新数据库
        userService.updateByPrimaryKeySelective(user);
        //更新user对象
        user = userService.selectByPrimaryKey(user.getUid());
        /*
        session.removeAttribute("user");
        System.out.println("暂时登出");
        */
        System.out.println("更新后的user" + user.toString());
        session.setAttribute("user", user);
        System.out.println("重新登陆");
        return "redirect:/user/home";
    }

    /*
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping("/upload2")
    public String userUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {
        User user = (User) session.getAttribute("user");
        //上传路径保存设置
        System.out.println("开始上传头像");
        String path = request.getServletContext().getRealPath("/static/images/avatar");
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址：" + realPath);

        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath + "/" + user.getUid() + ".png"));

        return "redirect:/user/home";
    }

    @GetMapping("/getpic")
    @ResponseBody
    public String getPic(HttpServletResponse response, HttpServletRequest request, int uid) throws Exception {
        String path = request.getServletContext().getRealPath("/static/images/avatar");
        String fileName = uid + ".png";
        String defaultfileName = "default.png";

        //1、设置response 响应头
        //response.reset(); //设置页面不缓存,清空buffer
        //response.setCharacterEncoding("UTF-8"); //字符编码
        //response.setContentType("multipart/form-data"); //二进制传输数据
        response.setContentType("image/png");
        /*
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
        */
        File file = new File(path, fileName);
        if (!file.exists()) {   //如果文件不存在
            file = new File(path, defaultfileName);
        }
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

    @RequestMapping("/repass")
    public String reUpass(Model model, HttpSession session, String nowpass, String pass, String repass) {
        User user = (User) session.getAttribute("user");
        Boolean warn = true;
        if (!user.getUpass().equals(nowpass)) {
            warn = false;
            model.addAttribute("nowpasswarn", "密码不对，再确认一下");
        }
        if (nowpass.equals(pass)) {
            warn = false;
            model.addAttribute("passwarn", "密码能再新一点吗");
        } else if (isLetterDigit(pass)) {
            warn = false;
            model.addAttribute("passwarn", "有奇怪的东西混进去了");
        } else if (!pass.equals(repass)) {
            warn = false;
            model.addAttribute("repasswarn", "再确认一下？");
        }
        if (!warn) {
            return "/user/set";
        }
        user.setUpass(pass);
        userService.updateByPrimaryKeySelective(user);
        user = userService.selectByPrimaryKey((user.getUid()));
        session.setAttribute("user", user);
        return "redirect:/user/home";
    }

    @RequestMapping(value = "/download")
    public String downloads(HttpServletResponse response, HttpServletRequest request) throws Exception {
        //要下载的图片地址
        String path = request.getServletContext().getRealPath("/upload");
        String fileName = "基础语法.jpg";

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path, fileName);
        //2、 读取文件--输入流
        InputStream input = new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        //4、执行 写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

    /*判断字符串是否仅限英文数字*/
    public static boolean isLetterDigit(String str) {
        String regex = "^[a-z0-9A-Z]+$";
        return !str.matches(regex);
    }

    public List<IndexView> ShowIndexView(List<Item> list) {
        List<IndexView> listview = new ArrayList<IndexView>();
        for (int i = 0; i < list.size(); i++) {
            //开始循环
            Item item = list.get(i);
            IndexView indexView = new IndexView();
            indexView.setIndexView(item, userService.selectByPrimaryKey(item.getUid()),
                    greatService.selectByIid(item.getIid()), commentService.selectByIid(item.getIid()));
            System.out.println(indexView.toString());
            //list中添加
            listview.add(indexView);
        }
        return listview;
    }

    public User setUserSex(User user) {
        if (user.getUsex().equals("m"))
            user.setUsex("男");
        else if (user.getUsex().equals("w"))
            user.setUsex("女");
        else if (user.getUsex().equals("s"))
            user.setUsex("保密");
        return user;
    }

    public Boolean checkUserSet(Model model, User user) {
        String uname = user.getUname();
        String uno = user.getUno();
        String upass = user.getUpass();
        String usex = user.getUsex();
        String utel = user.getUtel();
        Boolean warn = true;
        if (uno.length() == 0 || uno.length() > 16) {
            warn = false;
            model.addAttribute("nowarn", "账户长度不对哦");
        } else if (isLetterDigit(uno)) {
            warn = false;
            model.addAttribute("nowarn", "有奇怪的东西混进去了");
        } else if (userService.selectByUno(uno) != null) {
            warn = false;
            model.addAttribute("nowarn", "已经有friend叫这个名字了");
        }
        if (uname.length() == 0 || uname.length() > 16) {
            warn = false;
            model.addAttribute("namewarn", "昵称长度不对哦");
        }else if (userService.selectByUname(uname) != null) {
            warn = false;
            model.addAttribute("namewarn", "有frend叫这个名字了");
        }
        if (upass.length() < 6 || upass.length() > 18) {
            warn = false;
            model.addAttribute("passwarn", "密码长度不对哦");
        } else if (isLetterDigit(upass)) {
            warn = false;
            model.addAttribute("passwarn", "有奇怪的东西混进去了");
        }
        if (!(usex.equals("m") || user.equals("w") || usex.equals("s"))) {
            warn = false;
            model.addAttribute("sexwarn", "有奇怪的东西混进去了");
        }
        System.out.println("warn:" + warn);
        return warn;
    }
}
